<template>
  <div class="goods_body_page">
    <div class="page_title"> 商品中心 </div>
    <div class="search_box">
      <a-form :model="reqCategoryList" layout="inline">
        <a-form-item field="name" label="商品分类名称">
          <a-input
            v-model="reqCategoryList.name"
            placeholder="请输入商品分类名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button
            size="large"
            style="border-radius: 5px"
            @click="getCategoryList"
          >
            <template #icon>
              <a-image
                :src="require('@/assets/images/goods/search.png')"
                :width="20"
                :preview="false"
              />
            </template>
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    <div class="table_card">
      <div class="add_btn" @click="goodsModalRef.openModal('add', 0)">
        <svg
          t="1725542296927"
          class="add_icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="5163"
          style="overflow: visible"
        >
          <path
            d="M544 128a32 32 0 0 1 32 32V448h288a32 32 0 0 1 32 32v64a32 32 0 0 1-32 32H576v288a32 32 0 0 1-32 32h-64a32 32 0 0 1-32-32V576H160a32 32 0 0 1-32-32v-64a32 32 0 0 1 32-32H448V160a32 32 0 0 1 32-32h64z"
            fill="#1f1f1f"
            p-id="5164"
          ></path>
        </svg>
      </div>
      <a-table :columns="columns" :data="categoryList" style="margin-top: 50px">
        <template #options="{ record }">
          <a-popconfirm
            content="你希望删除该商品分类?"
            type="warning"
            @ok="okDeteleFn(record.id)"
          >
            <a-button class="btn_del">删除</a-button>
          </a-popconfirm>
          <a-button
            class="btn_edit"
            @click="goodsModalRef.openModal('edit', record.id)"
          >
            编辑
          </a-button>
          <a-button
            type="primary"
            status="success"
            style="margin-left: 10px"
            @click="goodsModalRef.openModal('add', record.id)"
          >
            新增商品分类
          </a-button>
        </template>
      </a-table>
    </div>
    <GoodsModal ref="goodsModalRef" @resetFn="resetFn" />
  </div>
</template>

<script setup lang="ts">
  import {
    getCategoryListAPI,
    type ReqCategoryList,
    deteleCategoryAPI,
  } from '@/api/goods';
  import { ref, onMounted, reactive } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { require } from '@/utils/require';
  import GoodsModal from './components/goodsModal.vue';
  onMounted(() => {
    getCategoryList();
  });

  const columns: TableColumnData[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: 'PID',
      dataIndex: 'pid',
      align: 'center',
    },
    {
      title: 'name',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      align: 'center',
    },
    {
      title: '',
      dataIndex: 'options',
      slotName: 'options',
      align: 'center',
    },
  ];

  const goodsModalRef = ref();

  const reqCategoryList = reactive<ReqCategoryList>({
    page: 1,
    page_size: 10,
    pid: null,
    name: '',
  });

  interface CategoryList {
    id: number;
    pid: number;
    name: string;
    create_time: string;
    upload_time?: string;
    children?: CategoryList[];
  }

  const categoryList = ref<CategoryList[]>([]);
  const getCategoryList = async () => {
    try {
      const { data } = (await getCategoryListAPI(reqCategoryList)).data;

      categoryList.value = buildTree(data.data);
    } catch (error) {
      Message.error('获取商品分类失败');
    }
  };

  // 重置状态
  const resetFn = () => {
    reqCategoryList.name = '';
    reqCategoryList.page = 1;
    reqCategoryList.pid = null;
    getCategoryList();
  };

  // 删除商品分类
  const okDeteleFn = async (id: number) => {
    try {
      const { code } = (await deteleCategoryAPI(id)).data;
      if (code == 200) {
        Message.success('删除商品分类成功');
        resetFn();
      } else {
        Message.error('删除商品分类失败');
      }
    } catch (error) {
      Message.error('删除商品分类失败');
    }
  };

  function buildTree(data: CategoryList[]) {
    const result: CategoryList[] = [];
    const map: { [key: number]: CategoryList } = {};
    data.forEach((item) => {
      map[item.id] = { ...item, children: [] };
    });

    console.log('map  ----->  ', map);

    data.forEach((item) => {
      if (item.pid === 0) {
        result.push(map[item.id]);
      } else {
        if (map[item.pid]) {
          map[item.pid].children!.push(map[item.id]);
        }
      }
    });

    result.forEach(cleanEmptyChildren);
    return result as CategoryList[];
  }

  function cleanEmptyChildren(node: CategoryList): void {
    if (node.children && node.children.length === 0) {
      delete node.children;
    } else if (node.children) {
      node.children.forEach(cleanEmptyChildren); // 递归清理子节点
    }
  }
</script>

<style lang="scss" scoped>
  .goods_body_page {
    padding: 15px;

    .page_title {
      margin-bottom: 15px;
      font-weight: bold;
      font-size: 20px;
    }

    .search_box {
      width: 100%;
      margin-bottom: 25px;
      padding: 10px;
      background-color: #fff;
      border-radius: 15px;
    }

    .table_card {
      position: relative;
      padding: 10px;
      background-color: #fff;

      .btn_del {
        z-index: 0;
        margin-right: 15px;
        color: #fff;
        background: red;
      }

      .btn_edit {
        z-index: 0;
        color: #fff;
        background: #ff9018;
      }

      .add_btn {
        position: absolute;
        right: 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 35px;
        height: 35px;
        overflow: hidden;
        background: #fff4e6;
        border-radius: 50%;
      }

      .add_btn:hover {
        width: 100px;
        background: linear-gradient(45deg, #2dc4d5, #44d4ac, #50d05e);
        border-radius: 17.5px;
        animation-duration: 0.3s;
      }

      .add_icon {
        width: 25px;
      }

      .add_btn:hover .add_icon {
        width: 35px;
        transform: translateY(30%);
        transition: transform 0.3s ease, fill 0.3s ease;
      }

      .add_btn:hover .add_icon path {
        transition: transform 0.3s ease, fill 0.3s ease;
        fill: #fff;
      }

      .add_btn::before {
        position: absolute;
        top: -50%;
        content: 'add';
      }

      .add_btn:hover::before {
        font-weight: bold;
        font-size: 13px;
        transform: translateY(120%);
        transition-duration: 0.3s;
      }
    }
  }
</style>
